package com.huifaapp.mall.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.google.gson.Gson;
import com.huifaapp.mall.R;
import com.huifaapp.mall.activity.HtmlActivity;
import com.huifaapp.mall.activity.JDred_packetActivity;
import com.huifaapp.mall.activity.MinuteKillActivity;
import com.huifaapp.mall.activity.Red_PacketActivity;
import com.huifaapp.mall.afinal.Constants;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.bean.JDlianjie;
import com.huifaapp.mall.bean.Minutekillshop;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.Contig;
import com.huifaapp.mall.uitils.UtilsImage;
import com.kepler.jd.Listener.LoginListener;
import com.kepler.jd.login.KeplerApiManager;
import com.kepler.jd.sdk.exception.KeplerBufferOverflowException;
import com.nostra13.universalimageloader.utils.L;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 
* @ClassName: IntroductionPageAdapter 
* @Description: TODO(引导页) 
* @author lijs
* @date 2016年5月11日 下午1:34:37 
*
 */
public class TabLayoutFragmentListviewAdapter extends BaseAdapter {
	private Context context;
	private LayoutInflater inflater;
	private List<Minutekillshop.DataBean.ListBean>  list;
	private IWXAPI api;
	private static final int SHARET_WXHY = 519;
	ArrayList<String> arrayList;
	private List<Boolean> isChecked;    //每个条目是否为选中
	private List<String> numbers;       //每个条目应显示的数字
	private List<Integer> checkedIndex;   //保存选中的下标
	private List<CheckBox> checkBox;      //保存选中的checkBox
	private int maxChecked = 9;       //最多选中几个
	private int checkedNumber = 0;    //选中的个数
	Integer Isspceial;
	private JDlianjie jDlianjiebean;
	private String datalisnajie;
	private int location;
	private String datayouhui;

	public TabLayoutFragmentListviewAdapter(Context context, List<Minutekillshop.DataBean.ListBean> list,Integer Isspceial){
		this.context = context;
		this.inflater = LayoutInflater.from(context);
		this.list=list;
		this.Isspceial=Isspceial;
		// 通过WXAPIFactory工厂，获取IWXAPI的实例
		api = WXAPIFactory.createWXAPI(context, Constants.WX_APPID);
		api.registerApp(Constants.WX_APPID);
		arrayList = new ArrayList<String>();
		isChecked = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			isChecked.add(false);
		}
		numbers = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			numbers.add("");
		}
		checkedIndex = new ArrayList<>();
		checkBox = new ArrayList<>();
	}

	@Override
	public int getCount() {
		return list == null ? 0 : list.size();
	//Integer.MAX_VALUE;
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}


	public List<Minutekillshop.DataBean.ListBean> getList() {
		return list;
	}

	public TabLayoutFragmentListviewAdapter setList(List<Minutekillshop.DataBean.ListBean> list) {
		this.list = list;
		return this;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;
		if (null == convertView) {
			convertView = inflater.inflate(R.layout.fragment_tablayout_listview, null);
			holder = new ViewHolder();
			holder.iv_tablayout_lv= (ImageView) convertView.findViewById(R.id.iv_tablayout_lv);
			holder.tv_tablayout_lv_name= (TextView) convertView.findViewById(R.id.tv_tablayout_lv_name);
			holder.tv_tablayout_lv_quan= (TextView) convertView.findViewById(R.id.tv_tablayout_lv_quan);
			holder.tv_tablayout_lv_zhengprice= (TextView) convertView.findViewById(R.id.tv_tablayout_lv_zhengprice);
			holder.tv_tablayout_lv_qianggou= (TextView) convertView.findViewById(R.id.tv_tablayout_lv_qianggou);
			holder.tv_tablayout_lv_yuanprice= (TextView) convertView.findViewById(R.id.tv_tablayout_lv_yuanprice);
			holder.tv_tablayout_lv_yishou= (TextView) convertView.findViewById(R.id.tv_tablayout_lv_yishou);
			holder.progressBarHorizontal= (ProgressBar)convertView. findViewById(R.id.progressBarHorizontal);
			holder.iv_jd_Or_yh= (ImageView) convertView.findViewById(R.id.iv_jd_Or_yh);
			holder.cb_checked_share_minkill= (CheckBox) convertView.findViewById(R.id.cb_checked_share_minkill);
			holder.ll_minutekill_details= (LinearLayout) convertView.findViewById(R.id.ll_minutekill_details);
			convertView.setTag(holder);

		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		//解决RecyclerView和checkBox问题
		holder.cb_checked_share_minkill.setTag(position);
		if (MinuteKillActivity.hmap.containsKey(position)) {
			holder.cb_checked_share_minkill.setChecked(MinuteKillActivity.hmap.get(position));
		} else {
			holder.cb_checked_share_minkill.setChecked(false);//true or false 都可以，看实际需求
		}
		Log.e("数据","list========="+list);
		final Minutekillshop.DataBean.ListBean bean=list.get(position);

		Log.e("数据","bean========="+bean);
		UtilsImage.uploadimageview(holder.iv_tablayout_lv,bean.getMainImageUrl(),"",context);
		holder.tv_tablayout_lv_name.setText("\t\t\t\t"+bean.getGoodsName());
		holder.tv_tablayout_lv_quan.setText("红包券¥"+bean.getCouponMoney());

		holder.tv_tablayout_lv_zhengprice.setText("¥"+bean.getWlPrice());
		Log.e("数据Contig.Isspceial",Isspceial+"");
		if(SPUtils.getInstance().getString(SPConstants.KEY_ISSTORE).equals("1")){
			holder.cb_checked_share_minkill.setVisibility(View.VISIBLE);
		}else{
			holder.cb_checked_share_minkill.setVisibility(View.GONE);
		}
//		if (Isspceial == 0) {
//			if (tabIstime.get(tab.getPosition()) == 1) {
//				holder.tv_tablayout_lv_qianggou.setText("已开抢");
//			} else if (tabIstime.get(tab.getPosition()) == 0) {
//				holder.tv_tablayout_lv_qianggou.setText("已结束");
//			} else {
//				holder.tv_tablayout_lv_qianggou.setText("已开抢");
//			}
//		} else if (Isspceial == 1) {
//			holder.tv_tablayout_lv_qianggou.setText("立即抢购");
//		} else if (Isspceial == 2) {
//			holder.tv_tablayout_lv_qianggou.setText("即将开始");
//		}
		if (Isspceial == 0) {
			holder.tv_tablayout_lv_qianggou.setText("已开抢");
		} else if (Isspceial == 1) {
			holder.tv_tablayout_lv_qianggou.setText("立即抢购");
		} else if (Isspceial == 2) {
			holder.tv_tablayout_lv_qianggou.setText("即将开始");
		}
		holder.tv_tablayout_lv_yuanprice.setText("原价¥"+bean.getPrice());
//		holder.tv_tablayout_lv_yuanprice.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG );
		if(bean.getSpuPlatform().equals("yh")){
			holder.iv_jd_Or_yh.setImageResource(R.drawable.youhui);
		}else if(bean.getSpuPlatform().equals("jd")){
			holder.iv_jd_Or_yh.setImageResource(R.drawable.jingdong);
		}
		holder.ll_minutekill_details.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				location = position;
				if (bean.getSpuPlatform().equals("yh")){
					Intent intent=new Intent(context,Red_PacketActivity.class);
					intent.putExtra("shopid",bean.getId());
					intent.putExtra("typex","yh");
					if(Isspceial==2){
						intent.putExtra("Isspceial","预热中");
					}else{
						intent.putExtra("Isspceial","立即购买");
					}
					context.startActivity(intent);
				} else {
					if (bean.getSpuPlatform().equals("jd")) {
						if ("".equals(bean.getCouponMoney() + "")) {
							initJDputong(bean.getId());
							if(KeplerApiManager.getWebViewService().isKeplerLogined()){
								try {
									KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
								} catch (KeplerBufferOverflowException e) {
									e.printStackTrace();
								}

							}else {
								final LoginListener mLoginListener = new LoginListener() {
									@Override
									public void authSuccess(Object token) {
										// TODO Auto-generated method stub
										Toast.makeText(context, token + "", Toast.LENGTH_SHORT).show();
										//                showToken();

										if (KeplerApiManager.getWebViewService().isKeplerLogined()) {
											try {
												KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
											} catch (KeplerBufferOverflowException e) {
												e.printStackTrace();
											}
										}

									}

									@Override
									public void authFailed(int errorCode) {
										// TODO Auto-generated method stub
										switch (errorCode) {
											case KeplerApiManager.KeplerApiManagerLoginErr_Init:// 初始化失败 break;
											case KeplerApiManager.KeplerApiManagerLoginErr_InitIng:// 初始化没有完成 break;
											case KeplerApiManager.KeplerApiManagerLoginErr_openH5authPageURLSettingNull://跳转url // 为null break;
											case KeplerApiManager.KeplerApiManagerLoginErr_getTokenErr:// 获取失败(OAuth授权之后，获取cookie过程出错) break;
											case KeplerApiManager.KeplerApiManagerLoginErr_User_Cancel:// 用户取消 break;
											case KeplerApiManager.KeplerApiManagerLoginErr_AuthErr_ActivityOpen://打开授权页面失败 break;
											default:
												break;
										}
//                Toast.makeText(AllOrderActivity.this, errorCode + ":authFailed", Toast.LENGTH_SHORT).show();
										Log.e("jdSHOUQUAN", errorCode + ":authFailed");
									}
								};
								KeplerApiManager.getWebViewService().login((Activity) context, mLoginListener);
							}
//							Intent intent = new Intent(context, HtmlActivity.class);
//							intent.putExtra("data", datalisnajie);
//							intent.putExtra("shopid", bean.getId());
//							context.startActivity(intent);
						}
						if ("" != bean.getCouponMoney() + "") {
							if (bean.getCouponMoney() == 0.0) {
								Map<String, String> map = new HashMap<>();
								map.put("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
								map.put("spuId", bean.getId());
								map.put("appid", AUniqueIdentifier.getDeviceId(context));
								Log.e("优惠二和一链接接口", ApiManager.BASE_NIUPAI_URL + "jd/getConUrl" + "?token=" + SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN) + "&spuId=" + bean.getId() + "&appid=" + AUniqueIdentifier.getDeviceId(context));
								OkHttpUtils.post().params(map).url(ApiManager.BASE_NIUPAI_URL + "jd/getConUrl").build().execute(new StringCallback() {


									@Override
									public void onError(com.squareup.okhttp.Request request, Exception e) {

									}

									@Override
									public void onResponse(String response) {
										Log.e("优惠二和一数据", response);
										Gson gson = new Gson();
										jDlianjiebean = gson.fromJson(response, JDlianjie.class);
										datayouhui = jDlianjiebean.getData();
										if (jDlianjiebean.getCode().equals("10000")) {
											Intent intent = new Intent(context, JDred_packetActivity.class);
											intent.putExtra("shopid", bean.getId());
											context.startActivity(intent);
										}
									}
								});
							} else {
								Map<String, String> map = new HashMap<>();
								map.put("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
								map.put("spuId", bean.getId());
								map.put("appid", AUniqueIdentifier.getDeviceId(context));

								OkHttpUtils.post().params(map).url(ApiManager.BASE_NIUPAI_URL + "jd/getConUrl").build().execute(new StringCallback() {


									@Override
									public void onError(com.squareup.okhttp.Request request, Exception e) {

									}

									@Override
									public void onResponse(String response) {
										Log.e("优惠二和一数据", response);
										Gson gson = new Gson();
										jDlianjiebean = gson.fromJson(response, JDlianjie.class);
										datayouhui = jDlianjiebean.getData();
										if (jDlianjiebean.getCode().equals("10000")) {
											if (jDlianjiebean.getData() != null) {
												if(KeplerApiManager.getWebViewService().isKeplerLogined()){
													try {
														KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
													} catch (KeplerBufferOverflowException e) {
														e.printStackTrace();
													}

												}else {
													final LoginListener mLoginListener = new LoginListener() {
														@Override
														public void authSuccess(Object token) {
															// TODO Auto-generated method stub
															Toast.makeText(context, token + "", Toast.LENGTH_SHORT).show();
															//                showToken();

															if (KeplerApiManager.getWebViewService().isKeplerLogined()) {
																try {
																	KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
																} catch (KeplerBufferOverflowException e) {
																	e.printStackTrace();
																}
															}

														}

														@Override
														public void authFailed(int errorCode) {
															// TODO Auto-generated method stub
															switch (errorCode) {
																case KeplerApiManager.KeplerApiManagerLoginErr_Init:// 初始化失败 break;
																case KeplerApiManager.KeplerApiManagerLoginErr_InitIng:// 初始化没有完成 break;
																case KeplerApiManager.KeplerApiManagerLoginErr_openH5authPageURLSettingNull://跳转url // 为null break;
																case KeplerApiManager.KeplerApiManagerLoginErr_getTokenErr:// 获取失败(OAuth授权之后，获取cookie过程出错) break;
																case KeplerApiManager.KeplerApiManagerLoginErr_User_Cancel:// 用户取消 break;
																case KeplerApiManager.KeplerApiManagerLoginErr_AuthErr_ActivityOpen://打开授权页面失败 break;
																default:
																	break;
															}
//                Toast.makeText(AllOrderActivity.this, errorCode + ":authFailed", Toast.LENGTH_SHORT).show();
															Log.e("jdSHOUQUAN", errorCode + ":authFailed");
														}
													};
													KeplerApiManager.getWebViewService().login((Activity) context, mLoginListener);
												}
//												Intent intent = new Intent(context, HtmlActivity.class);
//												intent.putExtra("shopid", bean.getId());
//												intent.putExtra("data", datayouhui);
//												context.startActivity(intent);

											}
										}
									}
								});


							}
						}

					}
					}
				}
		});
		try {


			//  不要动
			holder.cb_checked_share_minkill.setChecked(isChecked.get(position));
			holder.cb_checked_share_minkill.setText(numbers.get(position));
			holder.cb_checked_share_minkill.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					boolean check;
					if (checkedNumber < maxChecked) {
						if (!isChecked.get(position)) {
							checkedIndex.add(position);
							checkBox.add(holder.cb_checked_share_minkill);
							checkedNumber++;
							setText();
						} else {
							clearText(position, holder.cb_checked_share_minkill);
						}
						check = !isChecked.get(position);
					} else {
						if (checkedNumber == maxChecked && isChecked.get(position)) {
							clearText(position, holder.cb_checked_share_minkill);
						} else {
							Toast.makeText(context, "最多只能选" + maxChecked + "个", Toast.LENGTH_SHORT).show();
						}
						check = false;
					}
					isChecked.set(position, check);
					holder.cb_checked_share_minkill.setChecked(isChecked.get(position));
				}
			});
			Contig.checkedIndexminutekill=checkedIndex;
			Log.e("  ",Contig.checkedIndexminutekill+"                      "+checkedIndex );

		}catch (Exception e){
			Log.e("Exception",e.getMessage());
		}
		Log.e("特卖销售","bean.getTotalInventorys()=="+bean.getTotalInventorys()+"bean.getTotalSales()=="+bean.getTotalSales()
		+" bean.getTotalInventorys()=="+ bean.getTotalInventorys());
//		Double a=(bean.getTotalInventorys()-bean.getTotalSales())/bean.getTotalInventorys();
		try {
			int aa = (bean.getTotalInventorys() - bean.getTotalSales())*100 / bean.getTotalInventorys();
			if(aa<0){
				holder.tv_tablayout_lv_yishou.setText("仅剩" + 0 + "%");
				holder.progressBarHorizontal.setProgress(0);
			}else {
				holder.tv_tablayout_lv_yishou.setText("仅剩" + aa + "%");
				holder.progressBarHorizontal.setProgress(aa);
//			holder.progressBarHorizontal.setSecondaryProgress(aa+10);
			}
		}catch (Exception e){

		}

//		holder.iv_tablayout_lv_share.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				Intent intent=new Intent(context, WebJDShareActivity.class);
//				intent.putExtra("id",bean.getId());
//				context.startActivity(intent);
//			}
//		});
		return convertView;
	}
	//普通二和一链接0
	private void initJDputong(String id){
		Map<String,String>map=new HashMap<String, String>();
		map.put("spuId",id);
		map.put("appid", AUniqueIdentifier.getDeviceId(context));
		map.put("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
		Log.e("京东二合一转链",ApiManager.BASE_NIUPAI_URL+"jd/getUrl"+"?spuId="+id+"&appId="+AUniqueIdentifier.getDeviceId(context)+"&token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
		OkHttpUtils.post().params(map).url(ApiManager.BASE_NIUPAI_URL+"jd/getUrl").build().execute(new StringCallback() {

			@Override
			public void onError(com.squareup.okhttp.Request request, Exception e) {

			}

			@Override
			public void onResponse(String response) {
				Log.e("fgdgfe",response);
				Gson gson=new Gson();
				JDlianjie jDlianjie = gson.fromJson(response, JDlianjie.class);
				datalisnajie = jDlianjie.getData();
				Log.e("kfjsdkghdfk", datalisnajie);

			}
		});

	}
	public void clearText(int position, CheckBox cb_checked) {
		for (int i = 0; i < checkedIndex.size(); i++) {
			if (checkedIndex.get(i) == position) {
				numbers.set(position, "");
				checkedIndex.remove(i);
				checkBox.remove(i);
				break;
			}
		}
		checkedNumber--;
		setText();
		numbers.set(position, "");
		cb_checked.setText("");
	}

	public void setText() {
		for (int i = 0; i < checkedIndex.size(); i++) {
			numbers.set(checkedIndex.get(i), (i + 1) + "");
			checkBox.get(i).setText(numbers.get(checkedIndex.get(i)));
		}
	}



	class ViewHolder {
		private ImageView iv_tablayout_lv;
		private TextView tv_tablayout_lv_name;
		private TextView tv_tablayout_lv_zhengprice;
		private TextView tv_tablayout_lv_qianggou;
		private TextView tv_tablayout_lv_yuanprice;
		public ProgressBar progressBarHorizontal;
		private TextView tv_tablayout_lv_quan;
		private TextView tv_tablayout_lv_yishou;
		private CheckBox cb_checked_share_minkill;
		private ImageView iv_jd_Or_yh;
		private LinearLayout ll_minutekill_details;


	}
}